import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

Future<DateTime?> showDateTimePicker({
  required BuildContext context,
  DateTime? initialDate,
  DateTime? firstDate,
  DateTime? lastDate,
}) async {
  initialDate ??= DateTime.now();
  firstDate ??= DateTime(2020);
  lastDate ??= DateTime.now();

  // Pick the date
  final date = await showDatePicker(
    context: context,
    initialDate: initialDate,
    firstDate: firstDate,
    lastDate: lastDate,
  );

  if (date == null) return null;

  // Pick the time
  final time = await showTimePicker(
    context: context,
    initialTime: TimeOfDay.fromDateTime(initialDate),
  );

  if (time == null) return null;

  // Combine date and time
  return DateTime(date.year, date.month, date.day, time.hour, time.minute);
}

class DateTimeFormField extends StatelessWidget {
  final DateTime value;
  final String label;
  final Function(DateTime) onChanged;
  final String? Function(DateTime?)? validator;
  final bool showTime;
  final DateTime? firstDate;
  final DateTime? lastDate;

  const DateTimeFormField({
    Key? key,
    required this.value,
    required this.label,
    required this.onChanged,
    this.validator,
    this.showTime = true,
    this.firstDate,
    this.lastDate,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return FormField<DateTime>(
      initialValue: value,
      validator: validator,
      builder: (state) {
        return InkWell(
          onTap: () async {
            final picked = await showDateTimePicker(
              context: context,
              initialDate: value,
              firstDate: firstDate,
              lastDate: lastDate,
            );
            if (picked != null) {
              onChanged(picked);
              state.didChange(picked);
            }
          },
          child: InputDecorator(
            decoration: InputDecoration(
              labelText: label,
              errorText: state.errorText,
            ),
            child: Text(
              showTime
                  ? DateFormat('yyyy-MM-dd HH:mm').format(value)
                  : DateFormat('yyyy-MM-dd').format(value),
            ),
          ),
        );
      },
    );
  }
}
